package com.wsy.shiro.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.HashSet;
import java.util.Set;

/**
 * @author wangshangyi
 * @version V1.0  2020/8/27 17:37
 */
public class CustomRealm extends AuthorizingRealm {

    {
        super.setName("CustomRealm");
    }

    //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取用户名
        String username = (String) principalCollection.getPrimaryPrincipal();
        //获取用户角色
        Set<String> roles =  getUserRoleByUsername(username);
        //获取用户权限
        Set<String> Permissions = getUserPermissionsByUsername(username);
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(Permissions);
        return authorizationInfo;
    }

    private Set<String> getUserPermissionsByUsername(String username) {
        Set<String> Permissions = new HashSet<String>(2);
        Permissions.add("user:add");
        Permissions.add("user:select");
        return Permissions;
    }

    private Set<String> getUserRoleByUsername(String username) {
        Set<String> roles = new HashSet<String>(2);
        roles.add("admin");
        roles.add("user");
        return roles;
    }

    //认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取用户名
        String username = (String)authenticationToken.getPrincipal();
        //通过用户名到数据库中查询密码
        String password = getUserPasswordByName(username);
        SimpleAuthenticationInfo authorizationInfo = new SimpleAuthenticationInfo(username,password,"realmName");
        //将盐返回，用于验证
        authorizationInfo.setCredentialsSalt(ByteSource.Util.bytes("wsy"));
        return authorizationInfo;
    }

    /*假设数据库查到用户信息*/
    private String getUserPasswordByName(String username) {
//        return "123456";
        //返回加密之后的密码
//        return "827ccb0eea8a706c4c34a16891f84e7b";
        //加盐之后的密文
        return "a26f42e422f3379f543c2f31593673e7";
    }

    public static void main(String[] args) {
//        Md5Hash md5Hash= new Md5Hash("12345");
        //加盐
        Md5Hash md5Hash= new Md5Hash("12345","wsy");
        System.out.println(md5Hash);
    }
}
